<template>
  <!--啥也没有只是需要一个公共组件在初始化IM服务而已-->
</template>
<script>
  export default {
    name: "imInitPanel",
    data(){
      return {
        HEARTBEAT_TIME:this.$store.getters.getValForKey("HEARTBEAT_TIME"),
        clock:null,
        cmdLen:this.$store.getters.getValForKey("cmdLen"),
        CMD:this.$store.getters.getValForKey("CMD"),
        CMDHander:this.$store.getters.getValForKey("CMDHander"),
        CMDReverse:{},
        wsurl:location.protocol.indexOf("s")>=0?"wss:":"ws:"+"//"+this.proAPI.WS_DOMAIN+":9326/showcase",
      }
    },
    methods:{
      initWs(){
        //此处加上当前是否用户信息为空。若为空则不进行初始化链接
        if(this.$store.state.ws!=null){
          console.log("当前ws为"+this.$store.state.ws);
          return;
        }
        if(this.$store.getters.getUserInfo==null||this.$store.getters.getUserInfo.id==null){
          console.log("当前用户为"+this.$store.getters.getUserInfo);
          return;
        }

        this.initCMDReverse();
        this.$store.commit("initws",this.wsurl+"?id=c"+this.$store.getters.getUserInfo.id);
        this.$store.state.ws.onopen = (event, ws) => {
          this.ping();
        };
        this.$store.state.ws.onmessage = (event, ws) => {
          var arrayBuffer = event.data;
          console.log('receive data: ', arrayBuffer, ws)
          var uint8array = null;
          var firstbyte = new Uint8Array(arrayBuffer, 0, 2);
          var firstchar = new TextDecoder('utf-8').decode(firstbyte);
          var isZipped = false;
          var isZippedStr = '';
          if (firstchar.indexOf('x') != -1) {
            // 压缩过的
            isZipped = true;
            isZippedStr = '(zipped)';
            var zipedUint8array = new Uint8Array(arrayBuffer, 2);
            uint8array = pako.ungzip(zipedUint8array);
          } else {
            uint8array = new Uint8Array(arrayBuffer);
          }
          var data = new TextDecoder('utf-8').decode(uint8array);
          console.log('receive data' + isZippedStr + ': ' + data)
          if (!data || data.length < this.cmdLen) {
            console.error('data wrong' + isZippedStr + ', the data length must be >= ' + this.cmdLen, data);
            return;
          }
          var commandstr = data.substr(0, this.cmdLen);
          console.log(commandstr);
          var commandName = this.CMDReverse[commandstr];
          if (!commandName) {
            console.error('commandstr is ' + commandstr + isZippedStr + ', but con not find commandName');
            return;
          }
          if (!this.CMDHander[commandName]) {
            console.error('can not found siteImBsHandler, commandName is ' + commandName + isZippedStr);
            return;
          }
          if (data.length > this.cmdLen) {
            var bodyStr = data.substr(this.cmdLen);

            console.log('received:' + commandName + isZippedStr + '\r\n, body string is :' + bodyStr);
            var bodyObj = null;
            try {
              bodyObj = JSON.parse(bodyStr);
              console.log(bodyObj);
            } catch (error) {
              console.error(
                'can not parse to object, commandName is ' +
                commandName +
                isZippedStr +
                ', body string is ' +
                bodyStr
              );
              return;
            }
            // console.log("received " + commandName + ", body string is :" + bodyStr);
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, bodyStr, bodyObj,this.$store);
          } else {
            console.log('received:' + commandName + isZippedStr + ', body string is null');
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, null, null,this.$store);
          }
        };
        this.$store.state.ws.onclose = (event, ws) => {
          this.clock!=null?clearTimeout(this.clock):"";
        };
        this.$store.state.ws.onerror = (event, ws)=> {
          this.clock!=null?clearTimeout(this.clock):"";
        };
      },
      initCMDReverse(){
        for (var cmdName in this.CMD) {
          var commandValue = this.CMD[cmdName];
          this.CMDReverse[this.formatCommand(commandValue)] = cmdName;
        }
        console.log(this.CMDReverse);
      },
      sendInfo(command, bodyObj) {
        if(!this.$store.state.ws||this.$store.state.ws.readyState!=1){
          console.error("ws状态不正确");
          clearTimeout(this.clock);
          return;
        }
        var commandname = this.CMDReverse[command]; //HEARTBEAT_REQ
        var str = command;
        if (bodyObj) {
          str = command + JSON.stringify(bodyObj);
        }
        console.log('准备发送 ' + commandname + ":'" + str + "'");
        var uint8array = new TextEncoder().encode(str);
        this.$store.state.ws.send(uint8array.buffer);
      },
      ping(data){
        this.sendInfo(this.CMD.HEARTBEAT_REQ,null);
        this.clock = setTimeout(()=>{
          this.ping();
        },this.HEARTBEAT_TIME)
      },
      formatCommand(command){
        var commandstr = command + "";
        if (commandstr.length < this.cmdLen) {
          var gap = this.cmdLen - commandstr.length;
          var supplystr = "";
          for (var index = 0; index < gap; index++) {
            supplystr += "0";
          }
          if (command < 0) {
            commandstr = "-" + supplystr + commandstr.substring(1);
          } else {
            commandstr = supplystr + commandstr;
          }
        }
        // log("init command: " + command + ", fomatted command: " + commandstr);
        return commandstr;
      }
    },
    beforeCreate: function() {
    },
    created: function() {
    },
    beforeMount: function() {
    },
    mounted: function() {
      setTimeout(()=>{
        this.initWs();
      },2000)
    },
    beforeUpdate: function() {
    },
    updated: function() {
    },
    activated: function() {
      setTimeout(()=>{
        if(!this.$store.state.ws||this.$store.state.ws.readyState!=1){
          console.log("ws状态不正确,重新链接");
          this.$store.state.ws=null;
          this.initWs();
        }
      },1000)

    },
    deactivated: function() {
    },
    beforeDestroy: function() {
    },
    destroyed: function() {
    },
    errorCaptured: function(err, vm, info) {
    }
  }
</script>
<style scoped>

</style>
